home *** CD-ROM | disk | FTP | other *** search
- Path: locutus.rchland.ibm.com!usenet
- From: pstaite@vnet.ibm.com
- Newsgroups: comp.lang.c++
- Subject: Re: Q:order of evaluation
- Date: 16 Jan 1996 22:10:09 GMT
- Organization: IBM OS/2 Device Driver Development Rochester, MN
- Message-ID: <4dh7o1$bfi@locutus.rchland.ibm.com>
- References: <4dfhlu$a33$1@mhafn.production.compuserve.com>
- Reply-To: pstaite@vnet.ibm.com
- NNTP-Posting-Host: warpone.rchland.ibm.com
- X-Newsreader: IBM NewsReader/2 v1.2
-
- In <4dfhlu$a33$1@mhafn.production.compuserve.com>, Holger Maier <100336.3326@CompuServe.COM> writes:
- >Consider
- >#include <iostream>
- >int main() {
- > int i=1;int j=i+(i+=1);
- > cout<<i<<','<<j<<'\n';
- > return 0;
- >}
- >on my compiler this produces 2,4
- >Looked up the ARM:
- >5: .. The order of evaluation of subexpressions is determined by the
- >precedence and grouping of operators.
- >5.7: The additive operators + and - group left to right.
- >So, j should be assigned 3 ??
- >Now the question to you C++ gurus out there on the nets:
- >Is it really a compiler bug or is it just me misinterpreting the
- >ARM?
- >BTW: I know we should not code like that...
-
- Gads, not this thread again... Note in the ARM (hopefully somewhere
- close to where you found that part) it states something to the effect:
-
- "Order of evaluation of operands is undefined."
-
- Thus, while precedence and grouping solve the algebra of the operators,
- the evaluation of the variables and subexpressions that make up the
- operands is undefined. If you had:
-
- a = b + c + d;
-
- The compiler will evaluate/perform the + subexpression/operation between
- b and c first, then evaluate/perform the + subexpression/operation
- between the intermediate result and d. However, it may *evaluate* d
- first and put it in a register somewhere.
-
- Even in the case of:
-
- a = b + c * d;
-
- It must perform the multiplication before the addition. However, it can
- evaluate b first, it just cannot perform the addition until the
- multiplication is done.
-
- Therefore, getting back to your code, a compiler is free to load the
- value of i in a register, then evaluate (i+=1) then add the result to
- the register. This would produce an answer of 3. OTOH, the compiler
- could just as easily evaluate the () operand of + first, storing 2 in i,
- then add that to i and assign to j. This would produce 4.
-
- In short, you've modified an object (variable i) twice with no
- intervening sequence point. Therefore the result is undefined, it could
- assign 87 to j and that would be just fine (unexpected, but still
- legal ;-), undefined means anything goes.
-
-
- Phil Staite, team OS/2
- internet: pstaite@vnet.ibm.com internal: pstaite@rchland
-
-